/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jsf.generator;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.db.generator.JavaBaseClassWriter;

/**
 *
 * @author abosancic
 */
public class JavaPropertiesWriter extends JavaBaseClassWriter {

    protected StringBuilder stringFile = null;
    protected java.util.Properties properties;
    protected Locale locale = Locale.ENGLISH;
    
    public JavaPropertiesWriter() {
        super();
        stringFile = new StringBuilder();
    }

    public void setProperties(java.util.Properties properties) {
        this.properties = properties;
    }

    public void generateBundle() {
        stringFile.append("# bundle v1.0\n");
        if (properties != null) {
            for (String key : properties.stringPropertyNames()) {
                String value = properties.getProperty(key);
                try {
                    System.out.println("" + new String(key.getBytes(), "UTF-8"));
                    stringFile.append(new String(key.getBytes("UTF-8"), "UTF-8") + "=" + 
                            new String(value.getBytes("UTF-8"), "UTF-8"))
                            .append("\n");
                } catch (UnsupportedEncodingException ex) {
                    Logger.getLogger(JavaPropertiesWriter.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        stringFile.append("#end bundle");
        writeFile();
    }

    protected final synchronized void writeFile() {

        try {

            String path = "." + File.separator + "src" + File.separator;
            
            if (getPackageName() != null) {
                new File(path).mkdirs();
            }
            
            Writer out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(path + File.separator + "Bundle_" + locale.getLanguage() + ".properties"), "UTF-8"));
            out.append(stringFile.toString());
            out.flush();
            out.close();
            
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }

        stringFile = new StringBuilder();
    }

    public Locale getLocale() {
        return locale;
    }

    public void setLocale(Locale locale) {
        this.locale = locale;
    }

    
}
